// 在 store 中创建一个模块（WebSocket 模块）

function getToken(){
    return sessionStorage.getItem('Token')
}

const state = {
    ws: null,
    heartCheckTimer: null,
};

const mutations = {
    SET_WS(state, ws) {
        state.ws = ws;
        // console.log("SET_WS", state.ws);
    },
    CLEAR_WS(state) {
        state.ws = null;
    },
    SET_HEART_CHECK_TIMER(state, timer) {
        state.heartCheckTimer = timer;
    },
};

const actions = {
    startWebSocket({ commit, dispatch, state }) {
        if (getToken() && (!state.ws || state.ws.readyState !== WebSocket.OPEN)) {
            // console.log("SOCKET_PATH:", process.env);
            const socketUrl = `ws://127.0.0.1:9898`;
            // console.log(socketUrl);
            const ws = new WebSocket(socketUrl);

            ws.onmessage = function (e) {
                // console.log(`${new Date().toLocaleString()} >>>>> 收到消息 ${e.data}`, state.ws);
                if (e.data !== "pong") {
					console.log(e.data);
                    // Notification({
                    //     type: "info",
                    //     title: '新消息',
                    //     message: e.data,
                    //     position: "top-right",
                    //     duration: 3000,
                    //     showClose: true
                    // });
                }
            };

            ws.onclose = function () {
                console.log(`${new Date().toLocaleString()} >>>>> 连接已关闭`);
                // 尝试重新连接
                dispatch('reconnectWebSocket');
            };

            ws.onopen = function () {
                // console.log(`${new Date().toLocaleString()} >>>>> 连接成功`, ws);
				// Notification({
                //     type: "success",
                //     title: '成功',
                //     message: '会话连接成功',
                //     position: "top-right",
                //     duration: 3000,
                //     showClose: true
                // });
                // 保存 WebSocket 连接信息
                commit('SET_WS', ws);
                // // 在这里调用 sendWebSocketMessage，确保 state.ws 已经被正确设置
                // 开始心跳检测
                dispatch('startHeartCheck');
            };

            ws.onerror = function (e) {
                console.log(`${new Date().toLocaleString()} >>>>> 数据传输发生异常`, e);
                // Notification({
                //     type: "error",
                //     title: '错误',
                //     message: '会话连接异常，服务已断开',
                //     position: "top-right",
                //     duration: 3000,
                //     showClose: true
                // });
            };
        }
    },

    sendWebSocketMessage({ state }, msg) {
        // console.log(`${new Date().toLocaleString()} >>>>> 发送消息：${msg}`, state.ws);
        state.ws.send(msg);
    },

    reconnectWebSocket({ dispatch }) {
        dispatch('clearWebSocket');
        // 递归调用，一直尝试重连
        setTimeout(() => {
            dispatch('startWebSocket');
        }, 6000);
    },

    clearWebSocket({ commit, state }) {
        if (state.ws) {
            state.ws.close();
            commit('CLEAR_WS');
        }
    },

    startHeartCheck({ commit, dispatch, state }) {
        // console.log(`${new Date().toLocaleString()} >>>>> 开始心跳检测`, state.ws);
        // 清除之前的计时器
        dispatch('clearHeartCheckTimer');

        // 创建新的计时器
        dispatch('sendWebSocketMessage', 'ping');
        const timer = setInterval(() => {
            if (!state.ws || state.ws.readyState !== WebSocket.OPEN) {
                console.log(`${new Date().toLocaleString()} >>>>> 心跳检测失败,触发重连`, state.ws);
                dispatch('reconnectWebSocket');
            } else {
                // console.log(`${new Date().toLocaleString()} >>>>> 心跳正常,继续下一次心跳检测`, state.ws);
                dispatch('sendWebSocketMessage', 'ping');
            }
        }, 1000 * 29);
        commit('SET_HEART_CHECK_TIMER', timer);
    },

    clearHeartCheckTimer({ commit, state }) {
        const timer = state.heartCheckTimer;
        timer && clearInterval(timer);
        commit('SET_HEART_CHECK_TIMER', null);
    },
};

export default {
    // namespaced:true,
    state,
    mutations,
    actions,
};